//
//  WeiboCell.m
//  weibo-01
//
//  Created by HZApple on 16/5/11.
//  Copyright © 2016年 hdu. All rights reserved.
//

#import "WeiboCell.h"
#import "UIImageView+WebCache.h"
#import "NSDate+TimeAgo.h"
#import "ThemeManager.h"
#import "WXPhotoBrowser.h"

@interface WeiboCell()<WXLabelDelegate, PhotoBrowerDelegate>


@end

@implementation WeiboCell
//懒加载
- (NSMutableArray *)weiboImgViewArr {
    
    if (_weiboImgViewArr == nil) {
        
        _weiboImgViewArr = [NSMutableArray array];
        
        for (NSInteger i = 0; i < 9; i++) {
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectZero];
            
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            
            imgView.clipsToBounds = YES;

            imgView.userInteractionEnabled = YES;
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
             imgView.tag = i;
            [imgView addGestureRecognizer:tap];
            
            [self.contentView addSubview:imgView];
            
            [_weiboImgViewArr addObject:imgView];
        }
    }
    
    return _weiboImgViewArr;
    
}



- (UILabel *)reWeiboTextLabel {
    
    if (_reWeiboTextLabel == nil) {
        
        _reWeiboTextLabel = [[WXLabel alloc] initWithFrame:CGRectZero];
        _reWeiboTextLabel.wxLabelDelegate = self;
        _reWeiboTextLabel.font = [UIFont systemFontOfSize:15];
        _reWeiboTextLabel.numberOfLines = 0;
        
        [self.contentView addSubview:_reWeiboTextLabel];
        
        
    }
    
    return _reWeiboTextLabel;
}

- (ThemeImageView *)reWeiboBgImgView {
    
    if (_reWeiboBgImgView == nil) {
        
        _reWeiboBgImgView = [[ThemeImageView alloc] initWithFrame:CGRectZero];
        
        [self.contentView insertSubview:_reWeiboBgImgView atIndex:0];
    }
    
    return _reWeiboBgImgView;
}

- (UILabel *)weiboTextLabel {
    if (_weiboTextLabel == nil) {
        _weiboTextLabel = [[WXLabel alloc] initWithFrame:CGRectZero];
        _weiboTextLabel.wxLabelDelegate = self;
        _weiboTextLabel.font = [UIFont systemFontOfSize:16];
        _weiboTextLabel.numberOfLines = 0;
        [self.contentView addSubview:_weiboTextLabel];
    }
    return _weiboTextLabel;
}

- (UIImageView *)weiboImgView {
    
    if (_weiboImgView == nil) {
        _weiboImgView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self.contentView addSubview:_weiboImgView];
    }
    
    return _weiboImgView;
}


- (void)awakeFromNib {
    
    self.iconImaView.layer.cornerRadius = 5;
    self.iconImaView.layer.masksToBounds = YES;
    self.iconImaView.layer.borderColor = [UIColor grayColor].CGColor;
    self.iconImaView.layer.borderWidth = 0.5;
    
    
    _nickNameLabel.colorName = @"Timeline_Name_color";
    _publicTimeLabel.colorName = @"Timeline_Name_color";
    _sourseLabel.colorName = @"Timeline_Name_color";

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(themeChange) name:kThemeChangeNotification object:nil];
    

    
}

- (void)themeChange {
    
    self.weiboTextLabel.textColor = [[ThemeManager sharedManager] themeColorWithColorName:@"Timeline_Content_color"];
    self.reWeiboTextLabel.textColor = [[ThemeManager sharedManager] themeColorWithColorName:@"Detail_Content_color"];
    
}

- (void)setLayout:(WeiboCellLayout *)layout {
    
    _layout = layout;
    
    
    
    _nickNameLabel.text = _layout.weibo.user.name;
    
    //要进行将数据转化为时间
    _publicTimeLabel.text = [self parseWeiboDate:_layout.weibo.created_at];
    
    
    //将HTML数据提取
    _sourseLabel.text =  [self parseSourse:_layout.weibo.source];
    
    [_iconImaView sd_setImageWithURL:[NSURL URLWithString:_layout.weibo.user.profile_image_url]];
    
    self.weiboTextLabel.text = _layout.weibo.text;
    self.weiboTextLabel.textColor = [[ThemeManager sharedManager] themeColorWithColorName:@"Timeline_Content_color"];
    
    if (_layout.weibo.thumbnail_pic != nil) {
        [self showImgsWithUrls:_layout.weibo.pic_urls];
    }
    
    if (_layout.weibo.retweeted_status != nil) {
        
        //设置拉伸图片的左顶盖和上顶盖
        
        ThemeManager *manager = [ThemeManager sharedManager];
        UIImage *image = [manager themeImageWithImageName:@"timeline_rt_border_9"];
        image = [image stretchableImageWithLeftCapWidth:30 topCapHeight:20];
        self.reWeiboBgImgView.image = image;
        
        
        self.reWeiboTextLabel.text = _layout.weibo.retweeted_status.text;
        self.reWeiboTextLabel.textColor = [[ThemeManager sharedManager] themeColorWithColorName:@"Detail_Content_color"];
        
        if (_layout.weibo.retweeted_status.pic_urls != nil) {
            
            [self showImgsWithUrls:_layout.weibo.retweeted_status.pic_urls];
            //NSLog(@"%@",_layout.weibo.retweeted_status.pic_urls);
        }
    }
    

    self.weiboTextLabel.frame = _layout.weiboTextFrame;
    //self.weiboImgView.frame = _layout.weiboImgFrame;
    
    for (NSInteger i = 0; i < kImagesCount; i++) {
        
        UIImageView *imageView = self.weiboImgViewArr[i];
        imageView.frame = [_layout.weiboImgFrameArray[i] CGRectValue];
        //NSLog(@" %li  %@",i,NSStringFromCGRect(imageView.frame));
    }
    
    self.reWeiboTextLabel.frame = _layout.reWeiboTextFrame;
    self.reWeiboBgImgView.frame = _layout.reWeiboBgImgFrame;
    //NSLog(@"%@,%@",NSStringFromCGRect(_layout.reWeiboTextFrame),NSStringFromCGRect(_layout.reWeiboBgImgFrame));
    
    
    
}

- (void)showImgsWithUrls:(NSArray *)urls {
    
    for (NSInteger i = 0; i < urls.count; i++) {
        
        
        UIImageView *imgView = self.weiboImgViewArr[i];
        
        [imgView sd_setImageWithURL:[NSURL URLWithString:urls[i][@"thumbnail_pic"]]];
        
    }
   
}

- (NSString *)parseWeiboDate:(NSString *)dateStr {
    
    //1.字符串按照新浪微博提供的格式转化成NSDate
    //Sat May 14 13:43:58 +0800 2016
    
    NSString *formatter = @"E M d HH:mm:ss Z yyyy";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = formatter;
    
    //NSLog(@"%@", [NSLocale currentLocale].localeIdentifier);
    
    //dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    
    NSDate *publicDate = [dateFormatter dateFromString:dateStr];
    
    //2.计算发布微博时的时间戳
    //NSDate *currentDate = [NSDate date];
    
    //3.和当前时间比较计算出差值，再转成字符串输出
    //NSTimeInterval timerInterval = [currentDate timeIntervalSince1970] - [publicDate timeIntervalSince1970];
    
    return [publicDate timeAgo];
  
}

- (NSString *)parseSourse:(NSString *) string {
    
    NSInteger start = [string rangeOfString:@">"].location;
    
    NSInteger end = [string rangeOfString:@"<" options:NSBackwardsSearch].location;
    
    return [string substringWithRange:NSMakeRange(start + 1, end - start - 1)];
    
}

//- (void)setWeibo:(WeiboModel *)weibo {
//    
//    _weibo = weibo;
//    
//    _nickNameLabel.text = _weibo.user.name;
    //要进行将数据转化为时间
    //_publicTimeLabel.text = _weibo.created_at;
    //将HTML数据提取
    //_sourseLabel.text = _weibo.source;
//
//    [_iconImaView sd_setImageWithURL:[NSURL URLWithString:_weibo.user.profile_image_url]];
//    
//    
//    self.weiboTextLabel.text = _weibo.text;
//    
//    NSDictionary *attributes = @{
//                                 NSFontAttributeName:[UIFont systemFontOfSize:16]
//                                 };
//    
//    CGRect weiboTextRect = [self.weiboTextLabel.text boundingRectWithSize:CGSizeMake(kScreenWidth - 20, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes  context:NULL];
//    
//    self.weiboTextLabel.frame = CGRectMake(10, CGRectGetMaxY(_iconImaView.frame) + 10, kScreenWidth - 20, weiboTextRect.size.height);
//    
//
////    if (_Block) {
////        _Block(weiboTextRect.size.height);
////    }
//    
//}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma mark - wxlabeldelegate
- (NSString *)contentsOfRegexStringWithWXLabel:(WXLabel *)wxLabel {
    
    return @"(@[\\w-]{2,30}[\\s:])|(#[^#]+#)|(http(s)?://([A-Za-z0-9._-]+(/)?)*)";
    
    
}

- (UIColor *)linkColorWithWXLabel:(WXLabel *)wxLabel {
    
    return [[ThemeManager sharedManager] themeColorWithColorName:@"Link_color"];
}

//- (NSString *)imagesOfRegexStringWithWXLabel:(WXLabel *)wxLabel {
//    
//    
//    return nil;
//}
#pragma mark - 图片点击事件

- (void)tapAction:(UITapGestureRecognizer *)tap {

//    UIImageView *cellImgView = (UIImageView *)tap.view;
//    
//    CGRect rect = [cellImgView convertRect:cellImgView.bounds toView:nil];
//    UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
//    imgView.contentMode = UIViewContentModeScaleAspectFill;
//    imgView.clipsToBounds = YES;
//    imgView.image = cellImgView.image;
//    
//    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
//    backView.backgroundColor = [UIColor clearColor];
//    [backView addSubview:imgView];
//    
//    [self.window addSubview:backView];
//    
//    [UIView animateWithDuration:0.5 animations:^{
//         CGFloat height = kScreenWidth * imgView.image.size.height / imgView.image.size.width;
//        
//        CGFloat y = (kScreenHeight - height) / 2;
//        
//        imgView.frame = CGRectMake(0, y, kScreenWidth, height);
//    
//    }];
  
     [WXPhotoBrowser showImageInView:self.window selectImageIndex:tap.view.tag delegate:self];
    
}
#pragma mark - WXPhotoBrowser delegate
//需要显示的图片个数
- (NSUInteger)numberOfPhotosInPhotoBrowser:(WXPhotoBrowser *)photoBrowser {
    
    if (_layout.weibo.pic_urls.count > 0) {
        
        return _layout.weibo.pic_urls.count;
    } else {
        
        return _layout.weibo.retweeted_status.pic_urls.count;
    }
    
}

//返回需要显示的图片对应的Photo实例,通过Photo类指定大图的URL,以及原始的图片视图
- (WXPhoto *)photoBrowser:(WXPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    
    
    WXPhoto *photo = [[WXPhoto alloc] init];
    
    //拿到原图
   
    photo.srcImageView = self.weiboImgViewArr[index];
    
    //获取到大图的url
    
    NSArray *urls = nil;
    
    if (_layout.weibo.pic_urls.count > 0) {
        
        urls = _layout.weibo.pic_urls;
    } else {
        
        urls = _layout.weibo.retweeted_status.pic_urls;
    }
    
    NSLog(@"%@",urls[index][@"thumbnail_pic"]);
    
    NSString *imgURLString = urls[index][@"thumbnail_pic"];
    
    //大图的url
    imgURLString = [imgURLString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"large"];
    
    photo.url = [NSURL URLWithString:imgURLString];
    
    return photo;
    
    
}


#pragma mark - dealloc
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:kThemeChangeNotification];
}

@end
